from flask import jsonify
import re
from services.constants import PLATFORM_CONFIG

CONFIG_VALUE_MAP = {
    "list_display": [0, 1],
    "open_in_new_window": [True, False],
}

# 网站key转换
PLATFORM_KEY_MAP = {
    "fxBaoGao": PLATFORM_CONFIG["发现报告"]["id"],
    "xlWeiBo": PLATFORM_CONFIG["微博"]["id"],
    "zh": PLATFORM_CONFIG["知乎"]["id"],
    "dcDi": PLATFORM_CONFIG["懂车帝"]["id"],
    "itZhiJia": PLATFORM_CONFIG["IT之家"]["id"],
    "dy": PLATFORM_CONFIG["抖音热搜"]["id"],
    "ssPai": PLATFORM_CONFIG["少数派"]["id"],
    "36kr": PLATFORM_CONFIG["36氪"]["id"],
    "txXinWen": PLATFORM_CONFIG["腾讯新闻"]["id"],
    "bdTieBa": PLATFORM_CONFIG["百度贴吧"]["id"],
    "ppXinWen": PLATFORM_CONFIG["澎湃新闻"]["id"],
    "xfZuo": PLATFORM_CONFIG["小饭桌"]["id"],
}

def response_success(data):
    """成功响应格式化函数

    Parameters:
        data: 响应数据

    Returns:
        格式化后的响应数据
    """
    return jsonify({
        "success": True,
        "msg": "",
        "data": data
    })

def response_error(message):
    """错误响应格式化函数

    Parameters:
        msg: 错误信息
        code: 错误码

    Returns:
        格式化后的响应数据
    """
    return jsonify({
        "success": False,
        "msg": message,
        "data": None
    })

def is_page_out_of_bounds(page: int, page_size: int) -> bool:
    """判断分页是否合理"""
    if page < 1 or page_size < 1:
        return True
    return False

def is_valid_email(email: str) -> bool:
    """验证邮箱格式

    Parameters:
        email: 邮箱地址

    Returns:
        bool: 如果格式正确返回True，否则返回False
    """
    pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
    return re.match(pattern, email) is not None

def _check_subscription_exists(subscription_id: str) -> bool:
    """检查订阅项是否存在

    Parameters:
        subscription_id: 订阅项ID

    Returns:
        bool: 如果存在返回True，否则返回False
    """
    for platform in PLATFORM_CONFIG.values():
        if subscription_id in platform["id"]:
            return True
    return False

def remove_invalid_subscriptions(subscriptions: list) -> list:
    """剔除不存在的订阅项

    Parameters:
        subscriptions: 订阅项列表

    Returns:
        剔除后的订阅项列表
    """
    return [sub for sub in subscriptions if _check_subscription_exists(PLATFORM_KEY_MAP.get(sub, sub))]

def remove_invalid_config(config: dict) -> dict:
    """剔除不存在的配置项

    Parameters:
        config: 配置项字典

    Returns:
        剔除后的配置项字典
    """
    return {key: value for key, value in config.items() if key in CONFIG_VALUE_MAP and value in CONFIG_VALUE_MAP[key]}